var fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
var numbers = "12345678";
var lastmove = "";
var curmove = 0;

var imgpath = '/img/fantasy_shad/';

// Update the chessboard based on the FEN
function updateBoard() {
  var pos = fen.split(' ')[0];
  var rows = pos.split('/');
  var crow = $("#chessboard table tr:first");
  for (var i = 0; i < 8; i++) {
    updateRow(crow, rows[i]);
    crow = crow.next();
  }
}

// Update a row
function updateRow(row, str) {
  var cells = row.children();
  var p = 0;
  var i = 0;
  var img = "";
  while (i < 8) {
    if (numbers.indexOf(str[p]) >= 0) {
      sk = parseInt(str[p]);
      for (var j = 0; j < sk; j++) {
        cells[i].innerHTML = "";
        cells[i].abbr = "";
        
        i++;
      }
    }
    else {
      if (cells[i].abbr != str[p]) {
        
        cells[i].abbr = str[p];
  
        img = "";
        
        if (str[p] < 'z' && str[p] > 'a') img = "b";
        else img = "w";
        
        img += str[p].toLowerCase();
      
        img = imgpath + img + ".png";
        img = '<img src="' + img + '" width="40" height="40" />';
        cells[i].innerHTML = img;
        
      }
      i++;
    }
      
    p++;
  }
}

function updateLastMove(lmove) {
  var move;
  if (lastmove.length == 5) {
    move = lastmove.split("-");
    $("#" + move[0]).removeClass("lastmove");
    $("#" + move[1]).removeClass("lastmove");
  }
  lastmove = lmove;

  if (lastmove == "" ) return;
  
  move = lastmove.split("-");
  $("#" + move[0]).addClass("lastmove");
  $("#" + move[1]).addClass("lastmove");
}

$(document).ready(function() {
  updateBoard();
  $("span.move").click(function() {
    setMove(parseInt(this.id.substr(4)));
  });
});

function setMove(move) {
  $("span.currentmove").removeClass("currentmove");
  curmove = move;
  $("#move" + curmove).addClass("currentmove");
  getBoard();
}

function goToFirst() {
  setMove(0);
}

function goToNext() {
  if (curmove == movelength) return;
  setMove(++curmove);
}

function goToPrevious() {
  if (curmove == 0) return;
  setMove(--curmove);
}

function goToLast() {
  setMove(movelength);
}

function getBoard() {
  $.ajax({
    url: document.location.href,
    type: 'POST',
    data: {move: curmove},
    success: function(data, textStatus) {
      data = data.split("|")
      fen = data[0];
      updateBoard();
      updateLastMove(data[1]);
    }
  });
}
